package com.example.icongyou.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.icongyou.R;
import com.example.icongyou.adapter.TaskHeatAdapter;
import com.example.icongyou.adapter.TaskItemAdapter;
import com.example.icongyou.api.TaskDashboardApi;
import com.example.icongyou.bean.TaskDashboardBean;
import com.example.icongyou.bean.TaskHeatBean;
import com.example.icongyou.retrofit.RetrofitClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 任务数据看板页面：展示单课程任务信息、提交率、热度排名
 */
public class TaskDashboardActivity extends AppCompatActivity {
    // 页面控件
    private TextView tvCourseName;
    private ProgressBar progressBar;
    private TextView tvError;
    private RecyclerView rvTaskList;
    private View llHeatBoard;
    private RecyclerView rvViewHeat;
    private RecyclerView rvDiscussionHeat;

    // 适配器
    private TaskItemAdapter taskItemAdapter;
    private TaskHeatAdapter viewHeatAdapter;
    private TaskHeatAdapter discussionHeatAdapter;

    // 数据
    private String courseId; // 课程ID（从上一页面传递）
    private TaskDashboardApi taskDashboardApi;

    // 启动当前页面的便捷方法（供其他页面调用）
    public static Intent newIntent(Context context, String courseId) {
        Intent intent = new Intent(context, TaskDashboardActivity.class);
        intent.putExtra("courseId", courseId);
        return intent;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this); // 系统栏适配（与项目其他页面一致）
        setContentView(R.layout.activity_task_dashboard);

        // 处理系统栏间距（复用项目统一适配逻辑）
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.layout_task_dashboard_root), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 1. 获取从上一页面传递的课程ID
        getIntentData();

        // 2. 初始化控件
        initViews();

        // 3. 初始化 API 和适配器
        initApiAndAdapter();

        // 4. 设置选项卡切换监听（任务列表/热度看板）
        setTabSwitchListener();

        // 5. 加载数据
        loadTaskDashboardData();
        loadTaskHeatData();
    }

    /**
     * 获取从上一页面传递的参数
     */
    private void getIntentData() {
        Intent intent = getIntent();
        courseId = intent.getStringExtra("courseId");
        if (courseId == null || courseId.isEmpty()) {
            Toast.makeText(this, "课程ID不能为空", Toast.LENGTH_SHORT).show();
            finish(); // 参数错误，关闭页面
        }
    }

    /**
     * 初始化页面控件
     */
    private void initViews() {
        tvCourseName = findViewById(R.id.tv_course_name);
        progressBar = findViewById(R.id.progress_bar);
        tvError = findViewById(R.id.tv_error);
        rvTaskList = findViewById(R.id.rv_task_list);
        llHeatBoard = findViewById(R.id.ll_heat_board);
        rvViewHeat = findViewById(R.id.rv_view_heat);
        rvDiscussionHeat = findViewById(R.id.rv_discussion_heat);

        // 初始状态：显示任务列表，隐藏热度看板
        rvTaskList.setVisibility(View.VISIBLE);
        llHeatBoard.setVisibility(View.GONE);
        // 初始提示
        tvCourseName.setText("加载中...");
        tvError.setVisibility(View.GONE);
    }

    /**
     * 初始化 API 和适配器
     */
    private void initApiAndAdapter() {
        // 获取 API 实例（复用项目 Retrofit 配置）
        taskDashboardApi = RetrofitClient.getTaskDashboardApi();

        // 任务列表适配器
        taskItemAdapter = new TaskItemAdapter(this);
        rvTaskList.setLayoutManager(new LinearLayoutManager(this));
        rvTaskList.setAdapter(taskItemAdapter);

        // 查看热度适配器（标签：查看次数）
        viewHeatAdapter = new TaskHeatAdapter(this, "查看次数");
        rvViewHeat.setLayoutManager(new LinearLayoutManager(this));
        rvViewHeat.setAdapter(viewHeatAdapter);

        // 讨论热度适配器（标签：讨论次数）
        discussionHeatAdapter = new TaskHeatAdapter(this, "讨论次数");
        rvDiscussionHeat.setLayoutManager(new LinearLayoutManager(this));
        rvDiscussionHeat.setAdapter(discussionHeatAdapter);
    }

    /**
     * 设置选项卡切换监听
     */
    private void setTabSwitchListener() {
        RadioGroup rgTab = findViewById(R.id.rg_tab);
        rgTab.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rb_task_list) {
                // 切换到任务列表
                rvTaskList.setVisibility(View.VISIBLE);
                llHeatBoard.setVisibility(View.GONE);
            } else if (checkedId == R.id.rb_heat_board) {
                // 切换到热度看板
                rvTaskList.setVisibility(View.GONE);
                llHeatBoard.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     * 加载任务看板核心数据（任务信息+提交率）
     */
    private void loadTaskDashboardData() {
        showLoading();
        taskDashboardApi.getTaskDashboard(courseId).enqueue(new Callback<TaskDashboardBean>() {
            @Override
            public void onResponse(Call<TaskDashboardBean> call, Response<TaskDashboardBean> response) {
                hideLoading();
                if (response.isSuccessful() && response.body() != null) {
                    TaskDashboardBean dashboardBean = response.body();
                    // 更新课程名称
                    tvCourseName.setText("课程：" + dashboardBean.getCourseName());
                    // 更新任务列表数据
                    taskItemAdapter.setTaskList(dashboardBean.getTaskItems());
                } else {
                    showError("任务数据加载失败：" + response.code());
                }
            }

            @Override
            public void onFailure(Call<TaskDashboardBean> call, Throwable t) {
                hideLoading();
                showError("网络异常：" + t.getMessage());
            }
        });
    }

    /**
     * 加载任务热度数据（查看/讨论排名）
     */
    private void loadTaskHeatData() {
        showLoading();
        taskDashboardApi.getTaskHeatDashboard(courseId).enqueue(new Callback<TaskHeatBean>() {
            @Override
            public void onResponse(Call<TaskHeatBean> call, Response<TaskHeatBean> response) {
                hideLoading();
                if (response.isSuccessful() && response.body() != null) {
                    TaskHeatBean heatBean = response.body();
                    // 更新查看热度排名
                    viewHeatAdapter.setHeatList(heatBean.getViewHeatList());
                    // 更新讨论热度排名
                    discussionHeatAdapter.setHeatList(heatBean.getDiscussionHeatList());
                } else {
                    showError("热度数据加载失败：" + response.code());
                }
            }

            @Override
            public void onFailure(Call<TaskHeatBean> call, Throwable t) {
                hideLoading();
                showError("网络异常：" + t.getMessage());
            }
        });
    }

    /**
     * 显示加载中
     */
    private void showLoading() {
        progressBar.setVisibility(View.VISIBLE);
        tvError.setVisibility(View.GONE);
    }

    /**
     * 隐藏加载中
     */
    private void hideLoading() {
        progressBar.setVisibility(View.GONE);
    }

    /**
     * 显示错误信息
     */
    private void showError(String errorMsg) {
        tvError.setText(errorMsg);
        tvError.setVisibility(View.VISIBLE);
    }
}